package com.rzjm.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rzjm.api.config.RequestDataHelper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.netty.ClientSocket;
import com.rzjm.api.netty.SocketPool;
import com.rzjm.api.service.*;
import com.rzjm.api.util.*;
import com.rzjm.api.util.power.SmartPowerUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  设备相关接口
 *@Date 2018-05-10
 */
@Component
@RequestMapping("/device")//url:模块/资源/{}/细分
public class DeviceController extends BaseController {

    @Resource
    private ShopService shopService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private CkTerminalService ckTerminalService;
    @Resource
    private TerminalFittingService terminalFittingService;
    @Resource
    private TerminalTemperatureService temperatureService;
    @Resource
    private TerminalCheckRecordService terminalCheckRecordService;
    @Resource
    private TerminalCheckRecordImgService terminalCheckRecordImgService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private UserShopRelationService userShopRelationService;
    @Resource
    private SysDictService sysDictService;
    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceNodeService deviceNodeService;
    @Resource
    private RegFireCheckService regFireCheckService;
    @Resource
    private DeviceRangeService deviceRangeService;
    @Resource
    private DeviceRangeQrCodeService deviceRangeQrCodeService;
    @Resource
    private DeviceRangeFeedRecordService deviceRangeFeedRecordService;
    @Resource
    private DeviceRangeRecordService deviceRangeRecordService;
    @Resource
    private DeviceRangeResultService deviceRangeResultService;
    @Resource
    private DevicePowerRecordService devicePowerRecordService;
    @Resource
    private FsrDeviceService fsrDeviceService;
    @Resource
    private DevicePowerConsumptionService devicePowerConsumptionService;
    @Resource
    private DeviceWeldingRecordService deviceWeldingRecordService;
    @Resource
    private DeviceWeldingRecordImgService deviceWeldingRecordImgService;
    @Resource
    private DeviceWeldingService deviceWeldingService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private SmsTemplateService smsTemplateService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private FireWorkService fireWorkService;
    @Resource
    private SmokeAlarmInfoService smokeAlarmInfoService;
    @Resource
    private FeedService feedService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.voicePlayUrl}")
    private String voicePlayUrl;//图片地址


    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Resource
    private LockTemplate lockTemplate;

    @Value("${web.fsrParentAssetId}")
    private String fsrParentAssetId;

    /**
     *  制度列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/test")
    public JSONObject test(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "device/test 接收的参数： "+requestParam);
            System.out.println("device/test 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
//            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
//            int record_type = jsonRequest.containsKey("record_type") ? jsonRequest.getInt("record_type") : 0;

//            DeviceWeldingRecord record = deviceWeldingRecordService.findById(189);
//
//            DeviceWelding device = deviceWeldingService.findById(45);
//
//            wxTemplateService.sendWxMsgUseDeviceReg(record,device);

            FsrDevice fsrDevice = fsrDeviceService.findById("6c539fc364c603bbbawvfh");
//            QueryWrapper<DeviceRange> qw = new QueryWrapper<>();

//            String accessToken = wxTemplateService.getAccessToken("","",2);
//            JSONObject jsonObject = SmartPowerUtil.getDeviceList(fsrParentAssetId, accessToken);
//            System.out.println();


//            qw.eq("online_state", 1);
//            qw.lt("last_online_time", DateUtil.getAfterSecondsByOld(new Date(), -1200));
//            qw.orderByAsc("last_online_time");
//            List<DeviceRange> list = deviceRangeService.list(qw);
//            if(CollUtil.isNotEmpty(list)){
//                for (DeviceRange range : list){
//                    Date lastOnlineTime = range.getLastOnlineTime();
//                    //当前时间的  20分钟之前的时间   和最后在线时间对比
//                    Date checkTime = DateUtil.getAfterSecondsByOld(new Date(), -1200);
//                    if(lastOnlineTime.getTime() < checkTime.getTime()){
//                        range.setOnlineState(0);
//                        range.setLastOfflineTime(new Date());
//                        deviceRangeService.resetDevice(range);
//                    }
//                }
//            }


//            FireWork fireWork = fireWorkService.findById(1187);
//            DeviceWeldingRecord deviceRecord = deviceWeldingRecordService.findById(1498);
//            DeviceWelding welding = deviceWeldingService.findById(deviceRecord.getDeviceId());
//            wxTemplateService.sendWxMsgUseDeviceReg(deviceRecord,welding,fireWork,0);


//            fsrDeviceService.testDevice(fsrDevice);
            //先开闸
            fsrDeviceService.commandOp(fsrDevice,1);


//            QueryWrapper<DeviceWelding> qw = new QueryWrapper<>();
//            qw.eq("use_state",2);//使用中的
//            List<DeviceWelding> devices = deviceWeldingService.list(qw);
//            if(CollUtil.isNotEmpty(devices)){
//                for (DeviceWelding device : devices){
//                    if(device.getIsHasBreaker() == 1) {
//                        FsrDevice fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
//                        if (fsrDevice != null) {
//                            if(fsrDevice.getIsSelf() == 1){
//                                if((device.getUseState() == 2 && new Date().getTime() > device.getUseEndTime().getTime())
//                                        || (device.getUseState() == 0 && fsrDevice.getPowerCodeState() == 1)){
//                                    fsrDeviceService.commandOp(fsrDevice, 0);
//                                    device.setUseState(0);
//                                    deviceWeldingService.updateById(device);
//                                    System.out.println("企业焊机，执行关闭   执行时间： " + DateUtil.getTime());
//                                }
//                            }
//                        }
//                    }
//                }
//            }


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 距离测量测试
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/testRange",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject testRange(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/testRange 接收的参数： " + requestParam);
            logBefore(logger, " device/testRange 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            String order = jsonRequest.containsKey("order") ? jsonRequest.getStr("order") : "";
            String sn = jsonRequest.containsKey("sn") ? jsonRequest.getStr("sn") : "";
            String data = jsonRequest.containsKey("data") ? jsonRequest.getStr("data") : "";

            List<ClientSocket> clientSocketList = SocketPool.getClientByDeviceNum(sn);
            for (ClientSocket clientSocket : clientSocketList) {
                if (StrUtil.isNotEmpty(clientSocket.getTerminalNum()) && !clientSocket.getTerminalNum().equals("null")) {
                    //端口号,充电时间,订单编号
                    String orderParam = "MS" + order + sn + data + "ME";
                    System.out.println("命令： " + order + ": " + orderParam);
                    clientSocket.getChannel().writeAndFlush(orderParam);
                }
            }

            DeviceRange device = deviceRangeService.selectByUniqueColumn("device_num",sn);
            if(device != null){
                device.setDataCode(OrderUtil.getActiveNo());
                deviceRangeService.resetDevice(device);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     *  控制断电器
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/fsr/command",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject fsrCommand(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/fsr/command 接收的参数： " + requestParam);
            logBefore(logger, " device/fsr/command 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            String device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getStr("device_id") : null;
            int status = jsonRequest.containsKey("status") ? jsonRequest.getInt("status") : 0;

            FsrDevice device = fsrDeviceService.findById(device_id);
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            fsrDeviceService.commandOp(device,status);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     *  同步 菲舍尔的设备列表
     * @param
     * @throws Exception
     */
    @GetMapping(value="/sync/fsr")
    @ResponseBody
    public JSONObject syncFsrDevice() throws Exception{
        JSONObject result = null;
        try{
            fsrDeviceService.getDeviceListByApi();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 电焊机设备详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/detail")
    @ResponseBody
    public JSONObject weldingDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "device/welding/detail接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? Integer.parseInt(jsonRequest.getStr("user_id")) : 0;
            int device_id = jsonRequest.containsKey("device_id") ? Integer.parseInt(jsonRequest.getStr("device_id")) : 0;
            int fireWorkId = jsonRequest.containsKey("fireWorkId") ? Integer.parseInt(jsonRequest.getStr("fireWorkId")) : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceWelding device = deviceWeldingService.findById(device_id);
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }

            if(device.getIsSelf() == 0){
                SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
                if(sysUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定施工人员"),true,true);
                }

                Shop shop = shopService.findById(device.getShopId());
                if(shop!= null){
                    device.setShopName(shop.getShopName());
                }
                device.setLeaderName(sysUser.getName());
                device.setLeaderPhone(sysUser.getMobile());
                device.setCertificateNum(sysUser.getCertificateNum());
            }
            map.put("device",device);


            fsrDeviceService.initSearchDeviceStatus(device.getFsrBreakerId());



            FireWork fireWork = fireWorkService.findById(fireWorkId);
            if(fireWork != null){

                long[] hourCount = DateUtil.getDistanceTimes(fireWork.getFireBeginTime(), fireWork.getFireEndTime());
                fireWork.setHourCount((int)hourCount[1]);

                fireWork.setNowDate(DateUtil.getDayByDate(fireWork.getFireBeginTime()));
                fireWork.setBeginTime(DateUtil.getSimpleTime1(fireWork.getFireBeginTime()));

                map.put("fireWork",fireWork);

            }


            map.put("fireWorks",new ArrayList<>());
            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser != null){
//                if(sysUser.getIsTempWorker()!= null){
//                    map.put("is_temp_worker", sysUser.getIsTempWorker());
//                }
//                if(sysUser.getIsTempWorker() == 1){
//                    Date beginTime = sysUser.getTempBeginTime();
//                    Date endTime = sysUser.getTempBeginTime();
//
//                    if(new Date().getTime() < beginTime.getTime() || new Date().getTime() > endTime.getTime() ){
//                        map.put("is_expire", 1);
//                    }
//                }

                QueryWrapper<FireWork> qw = new QueryWrapper<>();
                qw.eq("reg_company_id", sysUser.getShopId());
                qw.eq("record_type", 0);
                qw.eq("state", 2);
                qw.eq("is_use", 0);
                qw.le("fire_begin_time", DateUtil.getTime(new Date()));
                qw.ge("fire_end_time", DateUtil.getTime(new Date()));
                List<FireWork> fireWorks = fireWorkService.list(qw);
                if(CollUtil.isNotEmpty(fireWorks)){
                }
                map.put("fireWorks",fireWorks);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/detail",e);
        }
        return result;
    }

    /**
     * 电焊机设备详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/record/detail")
    @ResponseBody
    public JSONObject recordDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "device/record/detail 接收的参数： "+requestParam);
            System.out.println("device/record/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? Integer.parseInt(jsonRequest.getStr("user_id")) : 0;
            int record_id = jsonRequest.containsKey("record_id") ? Integer.parseInt(jsonRequest.getStr("record_id")) : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceWeldingRecord deviceRecord = deviceWeldingRecordService.findById(record_id);
            if(deviceRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }

            if(deviceRecord.getIsSelf() == 0){
                Shop shop = shopService.findById(deviceRecord.getShopId());
                if(shop!= null){
                    deviceRecord.setShopName(shop.getShopName());
                }
            }
            map.put("record",deviceRecord);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/detail",e);
        }
        return result;
    }

    /**
     * 电焊机设备详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/active")
    @ResponseBody
    public JSONObject updateDevice(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "device/active接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? Integer.parseInt(jsonRequest.getStr("user_id")) : 0;
            int device_id = jsonRequest.containsKey("device_id") ? Integer.parseInt(jsonRequest.getStr("device_id")) : 0;
            String name = jsonRequest.containsKey("name") ? jsonRequest.getStr("name") : "";
            String phone = jsonRequest.containsKey("phone") ? jsonRequest.getStr("phone") : "";
            String certificate = jsonRequest.containsKey("certificate") ? jsonRequest.getStr("certificate") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceWelding device = deviceWeldingService.findById(device_id);
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }

            device.setState(1);
            device.setLeaderWxUserId(user_id);
            device.setLeaderName(name);
            device.setLeaderPhone(phone);
            device.setCertificateNum(certificate);

            boolean bl = deviceWeldingService.updateById(device);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"激活成功成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"更新失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/detail",e);
        }
        return result;
    }

    /**
     * 电焊机使用添加记录
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/add/record")
    @ResponseBody
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        logBefore(logger, "device/add/record接收的参数： "+requestParam);
        System.out.println("device/add/record接收的参数： "+requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? Integer.parseInt(jsonRequest.getStr("user_id")) : 0;
        int device_id = jsonRequest.containsKey("device_id") ? Integer.parseInt(jsonRequest.getStr("device_id")) : 0;
        int use_state = jsonRequest.containsKey("use_state") ? Integer.parseInt(jsonRequest.getStr("use_state")) : 1;
        Map<String,Object> map = new HashMap<>();

        LockInfo lockInfo = lockTemplate.lock(user_id + "_addWeldingRecord", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{

            int fire_work_id = jsonRequest.containsKey("fire_work_id") ? jsonRequest.getInt("fire_work_id") : 0;

            String beginTime = jsonRequest.containsKey("begin_time") ? jsonRequest.getStr("begin_time") : "";
            String endTime = jsonRequest.containsKey("end_time") ? jsonRequest.getStr("end_time") : "";
            String useAddress = jsonRequest.containsKey("use_address") ? jsonRequest.getStr("use_address") : "";


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceWelding device = deviceWeldingService.findById(device_id);
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }


            fsrDeviceService.initSearchDeviceStatus(device.getFsrBreakerId());

//            FireWork fireWork = fireWorkService.findById(fire_work_id);
//            if(fireWork == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请选择有效作业票"),true,true);
//            }
//
//            if(fireWork.getState() == 0){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该作业票未审核通过，请通过后操作"),true,true);
//            }
//            //DateUtil.getDateBeginTime(new Date(),0), DateUtil.getDateEndTime(new Date(),0)
//            if(
//               !(
//                        fireWork.getLastCheckTime().getTime() > DateUtil.getBeginDayDate(new Date(),0).getTime()
//                     && fireWork.getLastCheckTime().getTime() > DateUtil.getAfterDayDate(new Date(), 0).getTime()
//                )){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该作业票不符合有效期时间范围内，请重新选择"),true,true);
//            }

            FsrDevice fsrDevice = null;
            if(device.getIsHasBreaker() == 1) {
                fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                if(fsrDevice == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备绑定异常"),true,true);
                }
//                if(fsrDevice.getOnlineState() == 0){
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请把设备通电"),true,true);
//                }
            }

            SysUser sysUser = null;

            Department departmentSafe = null;

            if(device.getIsSelf() == 0){
                sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
                if(sysUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定施工人员"),true,true);
                }

                departmentSafe = departmentService.findById(sysUser.getDeptId());
                if(departmentSafe != null){
                    if(user.getIsTest() == 0 && departmentSafe.getDeptType() != 2){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无申请权限"),true,true);
                    }else{
                        if(StrUtil.isEmpty(sysUser.getCertificateNum())){
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请上传电焊工证书编号"),true,true);
                        }
                    }
                }
            }else{
                if(device.getState() == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请扫码激活设备"),true,true);
                }
            }

            if(use_state == 0 && device.getUseState() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备已归还，请发起借用申请"),true,true);
            } else if(use_state == 1 && device.getUseState() == 2){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备正在使用中，请归还后申请"),true,true);
            }

            if(use_state == 1){//申请使用
                if(device.getIsSelf() == 0) {
                    if (user.getIsTest() == 0 && sysUser.getShopId() != null && sysUser.getShopId().intValue() != device.getShopId().intValue()) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "暂无申请权限"), true, true);
                    }
                    device.setUseWorkerSysUserId(sysUser.getUserId());
                    device.setUseWorkerName(sysUser.getName());
                    device.setUseWorkerPhone(sysUser.getMobile());
                    device.setCertificateNum(sysUser.getCertificateNum());
                }else{
                    device.setUseWorkerName(device.getLeaderName());
                    device.setUseWorkerPhone(device.getLeaderPhone());
                }
            }else{//  申请归还 结束使用
                if(device.getIsSelf() == 0) {
                    device.setUseWorkerSysUserId(0L);
                    device.setUseWorkerName("");
                    device.setUseWorkerPhone("");
                    device.setCertificateNum("");
                }
            }

            if(device.getIsSelf() == 0) {
                device.setUseState(use_state);//申请中
            }else{
                if(use_state == 1){
                    device.setUseState(2);//申请中
                    device.setUseBeginTime(DateUtil.ConvertDateByformat(beginTime + ":00","yyyy-MM-dd HH:mm:ss"));
                    device.setUseEndTime(DateUtil.ConvertDateByformat(endTime+ ":59","yyyy-MM-dd HH:mm:ss"));
                }else{
                    device.setUseState(use_state);//申请中
                }
            }

            String companyName = "";
//            Company company = companyService.findById(device.getShopId());
            Shop shop = shopService.findById(device.getShopId());
            if(shop!= null){
                companyName = shop.getShopName();
            }
            boolean bl = deviceWeldingService.updateById(device);
            if(bl) {
                if(device.getIsSelf() == 1){//自有用户  扫码提交申请的时候，断开和 合闸 是一起执行的 先关后开
                    //先开闸
                    if(device.getIsHasBreaker() == 1) {
                        fsrDeviceService.commandOp(fsrDevice, 0);
//                        System.out.println("自由焊机，先执行关闭   执行时间： " + DateUtil.getTime());
                    }
                }
                DeviceWeldingRecord deviceRecord = new DeviceWeldingRecord();
                deviceRecord.setWxUserId(user_id);
                deviceRecord.setDeviceId(device_id);
                deviceRecord.setDeviceNum(device.getDeviceNo());
                deviceRecord.setDeviceName(device.getDeviceName());
                deviceRecord.setIsSelf(device.getIsSelf());
                deviceRecord.setCreateTime(new Date());
                deviceRecord.setShopId(device.getShopId());
                deviceRecord.setUseAddress(useAddress);
//                deviceRecord.setDepartCheckState(0);
                deviceRecord.setCheckSysUserId(0L);
                if(device.getIsSelf() == 0) {
                    deviceRecord.setWorkerName(sysUser.getName());
                    deviceRecord.setWorkerPhone(sysUser.getMobile());
                    deviceRecord.setCertificateNum(sysUser.getCertificateNum());
                }else{
                    deviceRecord.setWorkerName(device.getLeaderName());
                    deviceRecord.setWorkerPhone(device.getLeaderPhone());
                    deviceRecord.setCertificateNum(device.getCertificateNum());
                }

                deviceRecord.setUseState(use_state);
                if(use_state == 1){
                    deviceRecord.setUseBeginTime(DateUtil.ConvertDateByformat(beginTime+ ":00","yyyy-MM-dd HH:mm:ss"));
                    deviceRecord.setUseEndTime(DateUtil.ConvertDateByformat(endTime+ ":59","yyyy-MM-dd HH:mm:ss"));
                }

                deviceRecord.setDepartCheckState(0);
                if(use_state == 0){
                    deviceRecord.setState(1);
                    deviceRecord.setDepartCheckState(1);
                    if(shop != null){
                        deviceRecord.setShopName(shop.getShopName());
                    }
                }else{
                    if(device.getIsSelf() == 0){
                        deviceRecord.setState(0);
                        if(shop != null){
                            deviceRecord.setShopName(shop.getShopName());
                            departmentSafe = departmentService.getSafeDepart(shop.getId());
                            if(departmentSafe!=null){
                                //安全科部门
                                deviceRecord.setCheckDepartId(departmentSafe.getId());
                            }
                        }
                    }else{
                        deviceRecord.setDepartCheckState(1);
                        deviceRecord.setState(1);
                    }
                }
                bl = deviceWeldingRecordService.save(deviceRecord);
                if(bl){
                    if(use_state == 1){//申请使用

//                        fireWork.setIsUse(1);
//                        fireWorkService.updateById(fireWork);
                        if(device.getIsSelf() == 0){//企业用户  扫码提交申请的时候，先断开
                            //先开闸
                            if(device.getIsHasBreaker() == 1) {
                                fsrDeviceService.commandOp(fsrDevice, 0);
//                                System.out.println("企业焊机，执行关闭   执行时间： " + DateUtil.getTime());
                            }
                            smsTemplateService.sendSmsByToDianHanji(companyName+ " " + sysUser.getName());
                        }else{
                            //合闸
                            if(device.getIsHasBreaker() == 1) {
                                fsrDeviceService.commandOp(fsrDevice, 1);
                                System.out.println("自由焊机，后执行开启  执行时间： " + DateUtil.getTime());
                            }
                            smsTemplateService.sendSmsByToDianHanji("自有焊机");
                        }
                        wxTemplateService.sendWxMsgUseDeviceReg(deviceRecord,device, null,1);
                    }else{
                        //开闸
                        if(device.getIsHasBreaker() == 1) {
                            fsrDeviceService.commandOp(fsrDevice, 0);
//                            System.out.println("焊机，执行关闭   执行时间： " + DateUtil.getTime());
                        }
                    }
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功",deviceRecord.getId()),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/add/detail",e);
        } finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     * 电焊机使用添加记录(安全区域)
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/add/record/safe")
    @ResponseBody
    public JSONObject addRecordSafe(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();

        logBefore(logger, "device/add/record/safe 接收的参数： "+requestParam);
        System.out.println("device/add/record接收的参数： "+requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? Integer.parseInt(jsonRequest.getStr("user_id")) : 0;
        int device_id = jsonRequest.containsKey("device_id") ? Integer.parseInt(jsonRequest.getStr("device_id")) : 0;
        int use_state = jsonRequest.containsKey("use_state") ? Integer.parseInt(jsonRequest.getStr("use_state")) : 1;

        LockInfo lockInfo = lockTemplate.lock(user_id + "_addWeldingRecordSafe", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            String beginTime = jsonRequest.containsKey("begin_time") ? jsonRequest.getStr("begin_time") : "";
            String endTime = jsonRequest.containsKey("end_time") ? jsonRequest.getStr("end_time") : "";
            String useAddress = jsonRequest.containsKey("use_address") ? jsonRequest.getStr("use_address") : "";


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceWelding device = deviceWeldingService.findById(device_id);
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }

            Shop shop = shopService.findById(device.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }
//            if(device.getIsSafe() == 0){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备需要动火作业申请"),true,true);
//            }

            FsrDevice fsrDevice = null;
            if(device.getIsHasBreaker() == 1) {
                fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                if(fsrDevice == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备绑定异常"),true,true);
                }
//                if(fsrDevice.getOnlineState() == 0){
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请把设备通电"),true,true);
//                }
            }

            SysUser sysUser = null;
            Department departmentSafe = null;
            if(device.getIsSelf() == 0){
                sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
                if(sysUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定施工人员"),true,true);
                }

                departmentSafe = departmentService.findById(sysUser.getDeptId());
                if(departmentSafe != null){
                    if(user.getIsTest() == 0 && departmentSafe.getDeptType() != 2){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无申请权限"),true,true);
                    }else{
                        if(StrUtil.isEmpty(sysUser.getCertificateNum())){
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请上传电焊工证书编号"),true,true);
                        }
                    }
                }
            }else{
                if(device.getState() == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请扫码激活设备"),true,true);
                }
            }

            if(use_state == 0 && device.getUseState() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备已归还，请发起借用申请"),true,true);
            } else if(use_state == 1 && device.getUseState() == 2){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备正在使用中，请归还后申请"),true,true);
            }

            if(use_state == 1){//申请使用
                if(device.getIsSelf() == 0) {
                    if (user.getIsTest() == 0 && sysUser.getShopId() != null && sysUser.getShopId().intValue() != device.getShopId().intValue()) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "暂无申请权限"), true, true);
                    }
                    device.setUseWorkerSysUserId(sysUser.getUserId());
                    device.setUseWorkerName(sysUser.getName());
                    device.setUseWorkerPhone(sysUser.getMobile());
                    device.setCertificateNum(sysUser.getCertificateNum());
                }else{
                    device.setUseWorkerName(device.getLeaderName());
                    device.setUseWorkerPhone(device.getLeaderPhone());
                }
            }else{//  申请归还 结束使用
                if(device.getIsSelf() == 0) {
                    device.setUseWorkerSysUserId(0L);
                    device.setUseWorkerName("");
                    device.setUseWorkerPhone("");
                    device.setCertificateNum("");
                }
            }

            if(device.getIsSelf() == 0) {
                device.setUseState(use_state);//申请中
                device.setUseBeginTime(DateUtil.ConvertDateByformat(beginTime + ":00","yyyy-MM-dd HH:mm:ss"));
                device.setUseEndTime(DateUtil.ConvertDateByformat(endTime + ":59","yyyy-MM-dd HH:mm:ss"));
            }else{
                if(use_state == 1){
                    device.setUseState(2);//已申请
                    device.setUseBeginTime(DateUtil.ConvertDateByformat(beginTime + ":00","yyyy-MM-dd HH:mm:ss"));
                    device.setUseEndTime(DateUtil.ConvertDateByformat(endTime + ":59","yyyy-MM-dd HH:mm:ss"));
                }else{
                    device.setUseState(use_state);//申请中
                }
            }

            String companyName = "";
//            Shop shop = shopService.findById(device.getShopId());
            if(shop!= null){
                companyName = shop.getShopName();
            }

             try{
                 DeviceWeldingRecord deviceRecord = deviceWeldingRecordService.addRecordSafe(user_id,fsrDevice,sysUser,device,useAddress,use_state,shop);
                 if(deviceRecord != null){
                     if(use_state == 1){//申请使用
                         if(device.getIsSelf() == 0){//企业用户  扫码提交申请的时候，先断开
                             //先开闸
                             if(device.getIsHasBreaker() == 1) {
                                 fsrDeviceService.commandOp(fsrDevice, 0);
//                                 System.out.println("企业焊机，执行关闭   执行时间： " + DateUtil.getTime());
                             }
                             smsTemplateService.sendSmsByToDianHanji(companyName+ " " + sysUser.getName());
                         }else{
                             //合闸
                             if(device.getIsHasBreaker() == 1) {
                                 fsrDeviceService.commandOp(fsrDevice, 1);
                                 System.out.println("自由焊机，后执行开启  执行时间： " + DateUtil.getTime());
                             }
                             smsTemplateService.sendSmsByToDianHanji("自有焊机");
                         }
                         wxTemplateService.sendWxMsgUseDeviceReg(deviceRecord,device,null,1);
                     }else{
                         //开闸
                         if(device.getIsHasBreaker() == 1) {
                             fsrDeviceService.commandOp(fsrDevice, 0);
//                             System.out.println("焊机，执行关闭   执行时间： " + DateUtil.getTime());
                         }
                     }
                     result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功",deviceRecord.getId()),true,false);
                 }else{
                     result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
                 }
             }catch (Exception e){

             }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/add/detail",e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     * 电焊机使用添加记录
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/add/record/new")
    @ResponseBody
    public JSONObject addRecordNew(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();

        logBefore(logger, "device/add/record/new 接收的参数： " + requestParam);
        System.out.println("device/add/record/new 接收的参数： " + requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? Integer.parseInt(jsonRequest.getStr("user_id")) : 0;
        LockInfo lockInfo = lockTemplate.lock(user_id + "_addRecordNew", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            int device_id = jsonRequest.containsKey("device_id") ? Integer.parseInt(jsonRequest.getStr("device_id")) : 0;
            int use_state = jsonRequest.containsKey("use_state") ? Integer.parseInt(jsonRequest.getStr("use_state")) : 1;
            int fire_work_id = jsonRequest.containsKey("fire_work_id") ? jsonRequest.getInt("fire_work_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceWelding device = deviceWeldingService.findById(device_id);
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }


            Shop shop = shopService.findById(device.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }


            fsrDeviceService.initSearchDeviceStatus(device.getFsrBreakerId());

            FireWork fireWork = null;
            if(use_state == 1){
                //本设备之前绑定的作业票未验收的
                FireWork unYanShou = fireWorkService.getFireWorkByState(device_id,2);
                if(unYanShou != null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"有未验收的作业票，请验收后再申请"),true,true);
                }
            }

            fireWork = fireWorkService.findById(fire_work_id);
            if(fireWork == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请选择有效作业票"),true,true);
            }

            FsrDevice fsrDevice = null;
            if(device.getIsHasBreaker() == 1) {
                fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                if(fsrDevice == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备绑定异常"),true,true);
                }
//                if(fsrDevice.getOnlineState() == 0){
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请把设备通电"),true,true);
//                }
            }
            SysUser sysUser = null;
            Department departmentSafe = null;
            if(device.getIsSelf() == 0){
                sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
                if(sysUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定施工人员"),true,true);
                }

                departmentSafe = departmentService.findById(sysUser.getDeptId());
                if(departmentSafe != null){
                    if(user.getIsTest() == 0 && departmentSafe.getDeptType() != 2){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无申请权限"),true,true);
                    }else{
                        if(StrUtil.isEmpty(sysUser.getCertificateNum())){
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请上传电焊工证书编号"),true,true);
                        }
                    }
                }
            }else{
                if(device.getState() == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请扫码激活设备"),true,true);
                }
            }

            //结束使用的情况
//            if(use_state == 0 && device.getUseState() == 0){
//
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备已归还，请发起借用申请"),true,true);
//            }
            if(use_state == 1 && device.getUseState() == 2){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备正在使用中，请归还后申请"),true,true);
            }

            if(use_state == 1){//申请使用
                if(device.getIsSelf() == 0) {
                    if (user.getIsTest() == 0 && sysUser.getShopId() != null
                            && sysUser.getShopId().intValue() != device.getShopId().intValue()) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "暂无申请权限"), true, true);
                    }
                    device.setUseWorkerSysUserId(sysUser.getUserId());
                    device.setUseWorkerName(sysUser.getName());
                    device.setUseWorkerPhone(sysUser.getMobile());
                    device.setCertificateNum(sysUser.getCertificateNum());
                }else{
                    device.setUseWorkerName(device.getLeaderName());
                    device.setUseWorkerPhone(device.getLeaderPhone());
                }
            }else{//  申请归还 结束使用
                if(device.getIsSelf() == 0) {
                    device.setUseWorkerSysUserId(0L);
                    device.setUseWorkerName("");
                    device.setUseWorkerPhone("");
                    device.setCertificateNum("");
                }
            }

            if(device.getIsSelf() == 1){//自有用户  扫码提交申请的时候，断开和 合闸 是一起执行的 先关后开
                //先开闸
                if(device.getIsHasBreaker() == 1) {
                    fsrDeviceService.commandOp(fsrDevice, 0);
//                    System.out.println("自由焊机，先执行关闭   执行时间： " + DateUtil.getTime());
                }
            }

            String companyName = "";
//            Shop shop1 = shopService.findById(device.getShopId());
            if(shop != null){
                companyName = shop.getShopName();
            }

            try{
                DeviceWeldingRecord deviceRecord = deviceWeldingRecordService.addRecord(user_id,fsrDevice,sysUser,device,use_state,fireWork,shop);
                if(deviceRecord != null){
                    if(use_state == 1){//申请使用
                        if(device.getIsSelf() == 0){//企业用户  扫码提交申请的时候，先断开
                            //先开闸
                            if(device.getIsHasBreaker() == 1) {
                                fsrDeviceService.commandOp(fsrDevice, 0);
//                                System.out.println("企业焊机，执行关闭   执行时间： " + DateUtil.getTime());
                            }
                            smsTemplateService.sendSmsByToDianHanji(companyName+ " " + sysUser.getName());
                        }else{
                            //合闸
                            if(device.getIsHasBreaker() == 1) {
                                fsrDeviceService.commandOp(fsrDevice, 1);
                                System.out.println("自由焊机，后执行开启  执行时间： " + DateUtil.getTime());
                            }
                            smsTemplateService.sendSmsByToDianHanji("自有焊机");
                        }
                        wxTemplateService.sendWxMsgUseDeviceReg(deviceRecord,device,fireWork,0);
                    }else{
                        //开闸
                        if(device.getIsHasBreaker() == 1) {
                            fsrDeviceService.commandOp(fsrDevice, 0);
//                            System.out.println("焊机，执行关闭   执行时间： " + DateUtil.getTime());
                        }
                    }
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功",deviceRecord.getId()),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/add/detail",e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     * 电焊机设备详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/check/record")
    @ResponseBody
    public JSONObject checkRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();

        logBefore(logger, "device/check/record接收的参数： "+requestParam);
        System.out.println("device/check/record接收的参数： "+requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        LockInfo lockInfo = lockTemplate.lock(user_id + "_weldingCheckRecord", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            int check_state = jsonRequest.containsKey("check_state") ? jsonRequest.getInt("check_state") : 0;
            String check_result = jsonRequest.containsKey("check_result") ?jsonRequest.getStr("check_result") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有审核权限"),true,true);
            }

            Department departmentSafe = departmentService.findById(sysUser.getDeptId());
            if(departmentSafe == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您不属于安全科"),true,true);
            }

            DeviceWeldingRecord deviceRecord = deviceWeldingRecordService.findById(record_id);
            if(deviceRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该申请不存在"),true,true);
            }
            if(deviceRecord.getUseState() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"归还记录，无需审核"),true,true);
            }

            if(deviceRecord.getIsSelf() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该申请不需要审核"),true,true);
            }

            DeviceWelding device = deviceWeldingService.findById(deviceRecord.getDeviceId());
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审核设备不存在"),true,true);
            }

//            Shop shop = shopService.findById(device.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            FsrDevice fsrDevice = null;
            if(device.getIsHasBreaker() == 1) {
                fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                if(fsrDevice == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定断路器设备"),true,true);
                }
//                if(fsrDevice.getOnlineState() == 0){
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"断路器设备离线"),true,true);
//                }
            }


            /**
             * 0 - 待审核 1 - 审核通过 2 - 审核驳回
             */
            deviceRecord.setCheckSysUserId(sysUser.getUserId());
            deviceRecord.setDepartCheckUserName(sysUser.getName());
            deviceRecord.setDepartCheckState(check_state);
            deviceRecord.setDepartCheckResult(check_result);
            deviceRecord.setDepartCheckTime(new Date());
            if(check_state == 2){//审核驳回
                device.setUseState(0);
                deviceWeldingService.updateById(device);
            }else if(check_state == 1){
                //使用状态 0 - 未使用  1 - 申请中 2 - 审核通过使用中
                device.setUseState(2);

                //企业申请  通过后  修改 使用时间
                if(deviceRecord.getIsSelf() == 0){
                    device.setUseBeginTime(deviceRecord.getUseBeginTime());
                    device.setUseEndTime(deviceRecord.getUseEndTime());
                }

                deviceWeldingService.updateById(device);
            }

            boolean bl = deviceWeldingRecordService.updateById(deviceRecord);
            if(bl){
                if(check_state == 1) {//审核状态为 同意使用
                    if(device.getIsHasBreaker() == 1){
                        if(fsrDevice.getOnlineState() == 1){
                            //先开闸
                            fsrDeviceService.commandOp(fsrDevice,1);
                        }
                    }
                }else{
                    //不同意的情况下  关闭
                    if(device.getIsHasBreaker() == 1) {
                        fsrDeviceService.commandOp(fsrDevice, 0);
//                        System.out.println("焊机，执行关闭   执行时间： " + DateUtil.getTime());
                    }
                }
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"审核完成"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"审核失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/detail",e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     * 电焊机设备 生产经理审批
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/manager/check")
    @ResponseBody
    public JSONObject managerCheckRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        logBefore(logger, "device/check/record接收的参数： " + requestParam);
        System.out.println("device/check/record接收的参数： " + requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        LockInfo lockInfo = lockTemplate.lock(user_id + "_weldingManagerCheckRecord", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }
        try{
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            int check_state = jsonRequest.containsKey("check_state") ? jsonRequest.getInt("check_state") : 0;
            String check_result = jsonRequest.containsKey("check_result") ?jsonRequest.getStr("check_result") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }



            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有审核权限"),true,true);
            }


            DeviceWeldingRecord deviceRecord = deviceWeldingRecordService.findById(record_id);
            if(deviceRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该申请不存在"),true,true);
            }


            DeviceWelding device = deviceWeldingService.findById(deviceRecord.getDeviceId());
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审核设备不存在"),true,true);
            }

            Shop shop = null;
            try {
                shop = shopService.findById(user.getShopId());
                if(shop == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
                }
                if(shop.getState() == 0){
                    System.out.println(shop.getShopName() + " 企业已被禁用");
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

//            Shop shop = shopService.findById(device.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            if(deviceRecord.getManagerSysUserId().intValue() != sysUser.getUserId().intValue()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            if(deviceRecord.getIsSelf() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该申请不需要审核"),true,true);
            }

            FsrDevice fsrDevice = null;
            if(device.getIsHasBreaker() == 1) {
                fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
                if(fsrDevice == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定断路器设备"),true,true);
                }
            }

            try{
                int ret = deviceWeldingRecordService.managerCheckRecord(deviceRecord, sysUser, device,check_state,check_result);
                if(ret > 0){
                    if(check_state == 1) {//审核状态为 同意使用
                        if(device.getIsHasBreaker() == 1){
                            if(fsrDevice.getOnlineState() == 1){
                                //先开闸
                                fsrDeviceService.commandOp(fsrDevice,1);
                            }
                        }
                    }else{
                        //不同意的情况下  关闭
                        if(device.getIsHasBreaker() == 1) {
                            fsrDeviceService.commandOp(fsrDevice, 0);
//                            System.out.println("焊机，执行关闭   执行时间： " + DateUtil.getTime());
                        }
                    }
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"审核成功"),true,true);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"审核失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/detail",e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     *  安全科的审批列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/welding/record/list")
    @ResponseBody
    public JSONObject departRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "device/record/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);

            int user_id = jsonRequest.containsKey("user_id") ? Integer.parseInt(jsonRequest.getStr("user_id")) : 0;
            int state = jsonRequest.containsKey("state") ? Integer.parseInt(jsonRequest.getStr("state")) : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? Integer.parseInt(jsonRequest.getStr("pageSize")) : 1;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? Integer.parseInt(jsonRequest.getStr("pageIndex")) : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定管理人员"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            if(sysUser.getIsOpenWelding() == 0) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "模块未开启"), true, true);
            }

            int departType = 0;
            Department department = departmentService.findById(sysUser.getDeptId());
            if(department != null){
                departType = department.getDeptType();
//                if(departmentSafe.getDeptType() != 1){
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您不属于安全科"),true,true);
//                }
            }

            List<DeviceWeldingRecord> list = deviceWeldingRecordService.getRecordListByShop(state,user,sysUser,department,pageSize,pageIndex);

            map.put("records",list);
            map.put("departType",departType);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/welding/record/list",e);
        }
        return result;
    }

    /**
     * 距离测量测试
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/testRangeByNum",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject testRangeByNum(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/testRangeByNum 接收的参数： " + requestParam);
            logBefore(logger, " device/testRangeByNum 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
//            String device_num = jsonRequest.containsKey("device_num") ? jsonRequest.getStr("device_num") : 0;

            String order = jsonRequest.containsKey("order") ? jsonRequest.getStr("order") : "";
            String sn = jsonRequest.containsKey("sn") ? jsonRequest.getStr("sn") : "";
            String data = jsonRequest.containsKey("data") ? jsonRequest.getStr("data") : "";

            List<ClientSocket> clientSocketList = SocketPool.getClientByDeviceNum(sn);
            for (ClientSocket clientSocket : clientSocketList) {
                if (StrUtil.isNotEmpty(clientSocket.getTerminalNum()) && !clientSocket.getTerminalNum().equals("null")) {
                    //端口号,充电时间,订单编号
                    String orderParam = "MS" + order + sn + "" + data + "ME";
                    System.out.println("命令： " + order + ": " + orderParam);
                    clientSocket.getChannel().writeAndFlush(orderParam);
                }
            }

            DeviceRange device = deviceRangeService.selectByUniqueColumn("device_num",sn);
            if(device != null){
                device.setDataCode(OrderUtil.getActiveNo());
                deviceRangeService.resetDevice(device);
            }


            Shop shop = shopService.findById(device.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     * 距离测量测试
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/testData",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject testData(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/testData 接收的参数： " + requestParam);
            logBefore(logger, " device/testData 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);

            String sn = jsonRequest.containsKey("sn") ? jsonRequest.getStr("sn") : "";
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";

            //DeviceRangeRecord maxLength, DeviceRange deviceRange, String dataCode
            DeviceRangeRecord maxLength = deviceRangeRecordService.getMaxBevelByDeviceId(sn,code);

            DeviceRange device = deviceRangeService.selectByUniqueColumn("device_num",sn);
            deviceRangeRecordService.testData(maxLength,device,code);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     * 距离测量测试
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/startMeasure",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject startMeasure(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/startMeasure 接收的参数： " + requestParam);
            logBefore(logger, " device/startMeasure 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;

            String order = jsonRequest.containsKey("order") ? jsonRequest.getStr("order") : "";
            String sn = jsonRequest.containsKey("sn") ? jsonRequest.getStr("sn") : "";
            String data = jsonRequest.containsKey("data") ? jsonRequest.getStr("data") : "";

            List<ClientSocket> clientSocketList = SocketPool.getClientByDeviceNum(sn);
            for (ClientSocket clientSocket : clientSocketList) {
                if (StrUtil.isNotEmpty(clientSocket.getTerminalNum()) && !clientSocket.getTerminalNum().equals("null")) {
                    //端口号,充电时间,订单编号
                    String orderParam = "MS" + order + sn + data + "ME";
                    System.out.println("命令： " + order + ": " + orderParam);
                    clientSocket.getChannel().writeAndFlush(orderParam);
                }
            }

            DeviceRange device = deviceRangeService.findById(device_id);
            if(device != null){
                device.setDataCode(OrderUtil.getActiveNo());
                device.setLastOpUserId(user_id);
                deviceRangeService.resetDevice(device);
            }

            Shop shop = shopService.findById(device.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     * 维修终端设备列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/list",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/list 接收的参数： " + requestParam);
            logBefore(logger, " device/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_type = jsonRequest.containsKey("device_type") ? jsonRequest.getInt("device_type") : -1;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            int position = jsonRequest.containsKey("position") ? jsonRequest.getInt("position") : 1;
            int shopId = jsonRequest.containsKey("shopId") ? jsonRequest.getInt("shopId") : 1;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            if(device_type == -1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }

            Shop shop = shopService.findById(shopId);
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }


            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            List<Device> list = new ArrayList<>();
            list = deviceService.getDeviceList(user,device_type,position,shopId,pageIndex,pageSize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     * 维修终端设备列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/list/new",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject listNew(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/list/new 接收的参数： " + requestParam);
            logBefore(logger, " device/list/new 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;
            int device_type = jsonRequest.containsKey("device_type") ? jsonRequest.getInt("device_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            int position = jsonRequest.containsKey("position") ? jsonRequest.getInt("position") : 1;

            int shopId = jsonRequest.containsKey("shopId") ? jsonRequest.getInt("shopId") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

//            if(device_type == -1){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
//            }

            Shop shop = shopService.findById(shopId);
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }

            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            map.put("shop",shop);
            List<Device> list = new ArrayList<>();
            List<DeviceRange> rangeList = new ArrayList<>();
            int totalCount = 0;
            if(shop_type == 5){
                rangeList = deviceRangeService.getRangeListByShopId(user,shopId,device_type,pageIndex,pageSize);
                map.put("deviceList",rangeList);
                totalCount = rangeList.size();
            }else{
                list = deviceService.getDeviceList(user,device_type,position,shopId,pageIndex,pageSize);
                map.put("deviceList",list);
                totalCount = list.size();
            }
            List<Feed> feedList = new ArrayList<>();
            QueryWrapper<Feed> qw = new QueryWrapper<>();
            qw.eq("state", 1);
            List<Feed> feeds = feedService.list(qw);
            Feed feed = new Feed();
            feed.setId(-1);
            feed.setFeedName("清空");
            feedList.add(feed);
            if (feeds != null && feeds.size() > 0){
                feedList.addAll(feeds) ;
            }
            map.put("feedList",feedList);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",totalCount,map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     * 筒仓测量设备
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/list",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject rangeList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/list 接收的参数： " + requestParam);
            logBefore(logger, " device/range/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 0;
            int device_type = jsonRequest.containsKey("device_type") ? jsonRequest.getInt("device_type") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 1;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            Shop shop = shopService.findById(shop_id);
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            List<DeviceRange> list = deviceRangeService.getRangeListByShopId(user,shop_id,device_type,pageSize,pageIndex);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/range/list",e);
        }
        return result;
    }

    /**
     * 维修终端设备列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/testDevice",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject testDevice(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/testDevice 接收的参数： " + requestParam);
            logBefore(logger, " device/testDevice 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : -1;

            QueryWrapper<Device> qw = new QueryWrapper<>();
            qw.eq("device_type",2);
            List<Device> list = deviceService.list(qw);
            for (Device device : list){
                Date lastActiveTime = device.getLastActiveTime();
                Date checkTime = DateUtil.getAfterSecondsByOld(lastActiveTime,15 * 60);
                System.out.println("" + DateUtil.getTime(checkTime));
                //最后一次的交互时间已经超过了5分钟
                if(new Date().getTime() > checkTime.getTime()){
                    System.out.println("报警");
//                    wxTemplateService.sendWxMsgOffline(device);
                }
            }

//            Device device = deviceService.findById(device_id);
//            if(device != null){
//                wxTemplateService.sendWxMsgOffline(device);
//            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /** 设备的为温度记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/wenduList",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject wenduList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/wenduList 接收的参数： " + requestParam);
            logBefore(logger, "device/wenduList 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            String date = jsonRequest.containsKey("date") ? jsonRequest.getStr("date") : null;
            String beginHour = jsonRequest.containsKey("beginHour") ? jsonRequest.getStr("beginHour") : "00:00";
            String endHour = jsonRequest.containsKey("endHour") ? jsonRequest.getStr("endHour") : "23:59";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            String selectDate = "";
            if(date == null){
                selectDate = DateUtil.getDay();
            }else{
                selectDate = date;
            }
            Device device = deviceService.findById(device_id);
            if(device  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }


            Shop shop = shopService.findById(device.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            List<Map<String,Object>> allList = new ArrayList<>();
            List<DeviceNode> nodes = deviceNodeService.selectListByColumn("device_id",device_id);
            if(CollUtil.isNotEmpty(nodes)){
                for (DeviceNode node : nodes){
                    if(node.getDeviceType() == 2){
                        Map<String,Object> mapReturn = temperatureService.getChartDataByNode(device_id, selectDate,beginHour,endHour,node);
                        allList.add(mapReturn);
                    }else{
                        Map<String,Object> mapReturn = temperatureService.getChartDataByNode(device_id, selectDate,beginHour,endHour,node);
                        allList.add(mapReturn);
                    }
                }
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",allList),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/wenduList",e);
        }
        return result;
    }

    /** 设备的为温度记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/wenduRecord",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject wenduRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/wenduRecord 接收的参数： " + requestParam);
            logBefore(logger, "device/wenduRecord 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int page_index = jsonRequest.containsKey("page_index") ? jsonRequest.getInt("page_index") : 1;
            int page_size = jsonRequest.containsKey("page_size") ? jsonRequest.getInt("page_size") : 15;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(1,"该用户信息不存在"),true,true);
            }

            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            QueryWrapper<TerminalTemperature> qw = new QueryWrapper<>();
            qw.eq("device_id",device_id);
            qw.orderByDesc("create_time");
            List<TerminalTemperature> list = temperatureService.getPageEntityList(qw,page_index,page_size);
            if(CollUtil.isNotEmpty(list)){
                for (TerminalTemperature terminalTemperature : list){

                    QueryWrapper<DeviceNode> qwNode = new QueryWrapper<>();
                    qwNode.eq("device_id",terminalTemperature.getDeviceId());
                    qwNode.eq("node_index",terminalTemperature.getNodeIndex());
                    qwNode.eq("ins_index",terminalTemperature.getInsIndex());
                    qwNode.last("limit 1");
                    DeviceNode deviceNode = deviceNodeService.getOne(qwNode);
                    if(deviceNode!=null){
                        terminalTemperature.setNodeName(deviceNode.getTerminalName());
                        terminalTemperature.setDeviceType(deviceNode.getDeviceType());
                        terminalTemperature.setPowerState(deviceNode.getPowerState());
                        terminalTemperature.setPowerOffTime(deviceNode.getPowerOffTime());
                        terminalTemperature.setPowerOpenTime(deviceNode.getPowerOpenTime());

                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/recordlist",e);
        }
        return result;
    }

    /** 设备的为温度记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/wenduRecordNew",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject wenduRecordNew(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/wenduRecordNew 接收的参数： " + requestParam);
            logBefore(logger, "device/wenduRecordNew 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int node_id = jsonRequest.containsKey("node_id") ? jsonRequest.getInt("node_id") : 0;
            int page_index = jsonRequest.containsKey("page_index") ? jsonRequest.getInt("page_index") : 1;
            int page_size = jsonRequest.containsKey("page_size") ? jsonRequest.getInt("page_size") : 15;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(1,"该用户信息不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            DeviceNode deviceNode = null;
            Map<String,Object> map = new HashMap<>();
            List<DeviceNode> nodes = deviceNodeService.selectListByColumn("device_id",device_id);
            map.put("nodes",nodes);
            if(node_id > 0){
                deviceNode = deviceNodeService.findById(node_id);
            }else{
                deviceNode = nodes.get(0);
            }


            QueryWrapper<TerminalTemperature> qw = new QueryWrapper<>();
            qw.eq("device_id",device_id);
            qw.gt("wendu",0);
            if(deviceNode!=null){
                qw.eq("node_index",deviceNode.getNodeIndex());
                qw.eq("ins_index",deviceNode.getInsIndex());
            }
            qw.orderByDesc("create_time");
            List<TerminalTemperature> list = temperatureService.getPageEntityList(qw,page_index,page_size);
            if(CollUtil.isNotEmpty(list)){
                for (TerminalTemperature terminalTemperature : list){
                    if(deviceNode!=null){
                        terminalTemperature.setNodeName(deviceNode.getTerminalName());
                        terminalTemperature.setDeviceType(deviceNode.getDeviceType());
                        terminalTemperature.setPowerState(deviceNode.getPowerState());
                        terminalTemperature.setPowerOffTime(deviceNode.getPowerOffTime());
                        terminalTemperature.setPowerOpenTime(deviceNode.getPowerOpenTime());
                    }
                }
            }

            map.put("records",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/recordlist",e);
        }
        return result;
    }

    /**
     * 粮仓温度图表数据
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/result/record",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject rangeResultRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/record 接收的参数： " + requestParam);
            logBefore(logger, "device/range/record 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            String begin_date = jsonRequest.containsKey("begin_date") ? jsonRequest.getStr("begin_date") : "";
            String end_date = jsonRequest.containsKey("end_date") ? jsonRequest.getStr("end_date") : "";

            int page_index = jsonRequest.containsKey("page_index") ? jsonRequest.getInt("page_index") : 1;
            int page_size = jsonRequest.containsKey("page_size") ? jsonRequest.getInt("page_size") : 15;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceRange deviceRange = deviceRangeService.findById(device_id);
            if(deviceRange  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }


            Map<String,Object> map = new HashMap<>();
            QueryWrapper<DeviceRangeResult> qw = new QueryWrapper<>();
            qw.eq("device_id",device_id);
            if(StrUtil.isNotEmpty(begin_date)){
                qw.between("create_time", begin_date + " 00:00:00" ,end_date + " 23:59:59");
            }
            if(user.getIsTest() == 0){
                qw.eq("is_test",0);
            }
            qw.orderByDesc("create_time");
            List<DeviceRangeResult> list = deviceRangeResultService.getPageEntityList(qw,page_index,page_size);
            for (DeviceRangeResult result1 : list){
//                if(result1.getDeviceType() == 0){
//                }
                result1.setIsShowFull(deviceRange.getIsShowFull());
                result1.setIsShowEmpty(deviceRange.getIsShowEmpty());
                if(result1.getHumidity() == null || (result1.getHumidity()!= null && result1.getHumidity().equals("0"))){
                    result1.setTemperature(MathUtil.getDoubleUp(Double.parseDouble(result1.getTemperature()) * 0.1)+"");
                }

                if(result1.getWeightNew()!= null && result1.getWeightNew()> 0){
                    result1.setTotalWeightDunNew(MathUtil.getDoubleUpThree((result1.getWeight() + result1.getWeightNew()) / 1000));
                }

                result1.setWeight(MathUtil.getDoubleUpThree(result1.getWeight() / 1000));

            }

            map.put("records",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/range/record",e);
        }
        return result;
    }

    /**record
     * 粮仓温度图表数据
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/result/chart",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject rangeResultChart(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/result/chart 接收的参数： " + requestParam);
            logBefore(logger, "device/range/result/chart 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            String begin_date = jsonRequest.containsKey("begin_date") ? jsonRequest.getStr("begin_date") : "";
            String end_date = jsonRequest.containsKey("end_date") ? jsonRequest.getStr("end_date") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceRange deviceRange = deviceRangeService.findById(device_id);
            if(deviceRange  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }

            Shop shop = shopService.findById(deviceRange.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }


            Map<String,Object> mapReturn = deviceRangeResultService.getChartDataByDeviceRange(user,deviceRange,begin_date,end_date);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",mapReturn),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/range/result/chart",e);
        }
        return result;
    }

    /**
     * 粮仓温度图表数据
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/chart",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject rangeChart(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/chart 接收的参数： " + requestParam);
            logBefore(logger, "device/range/chart 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            String device_num = jsonRequest.containsKey("device_num") ? jsonRequest.getStr("device_num") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceRange deviceRange = deviceRangeService.findById(device_id);
            if(deviceRange  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }


            Shop shop = shopService.findById(deviceRange.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            Map<String,Object> map = new HashMap<>();

            Map<String,Object> mapReturnLast = deviceRangeRecordService.getChartDataByDeviceRange(user,deviceRange);
            map.put("lastData",mapReturnLast);

            String begin_date = DateUtil.getMonthStr(new Date()) + "-01";
            String end_date = DateUtil.getDayStr(new Date());

            Map<String,Object> mapReturnResult = deviceRangeResultService.getChartDataByDeviceRange(user,deviceRange,begin_date,end_date);

            map.put("resultData",mapReturnResult);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/range/chart",e);
        }
        return result;
    }

    /**
     * 粮仓温度图表数据
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/record/chart",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject rangeRecordChart(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/chart 接收的参数： " + requestParam);
            logBefore(logger, "device/range/chart 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            String device_num = jsonRequest.containsKey("device_num") ? jsonRequest.getStr("device_num") : "";
            String data_code = jsonRequest.containsKey("data_code") ? jsonRequest.getStr("data_code") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceRange deviceRange = deviceRangeService.findById(device_id);
            if(deviceRange  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }


            Shop shop = shopService.findById(deviceRange.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            Map<String,Object> map = new HashMap<>();

            Map<String,Object> mapReturnLast = deviceRangeRecordService.getChartDataByDeviceRangeByDataCode(user,deviceRange,data_code);
            map.put("lastData",mapReturnLast);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/range/chart",e);
        }
        return result;
    }

    /**
     * 设备的上电断电记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/powerRecord",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject powerRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/powerRecord 接收的参数： " + requestParam);
            logBefore(logger, "device/powerRecord 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int node_id = jsonRequest.containsKey("node_id") ? jsonRequest.getInt("node_id") : 0;
            int page_index = jsonRequest.containsKey("page_index") ? jsonRequest.getInt("page_index") : 1;
            int page_size = jsonRequest.containsKey("page_size") ? jsonRequest.getInt("page_size") : 15;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(1,"该用户信息不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            QueryWrapper<TerminalTemperature> qw = new QueryWrapper<>();
            qw.eq("device_id",device_id);
            if(node_id > 0){
                qw.eq("node_id", node_id);
            }
            qw.orderByDesc("create_time");
            List<DevicePowerRecord> list = devicePowerRecordService.getPageEntityList(qw,page_index,page_size);

            Map<String,Object> map = new HashMap<>();
            map.put("records",list);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/powerRecord",e);
        }
        return result;
    }

    /**
     * 动火申请
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/fireReg",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject fireReg(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/fireReg 接收的参数： " + requestParam);
            logBefore(logger, " device/fireReg 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            List<Device> list = deviceService.getDeviceList(user,1,0,0,1,100);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     * 动火申请列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/fireRegList",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject fireRegList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/fireRegList 接收的参数： " + requestParam);
            logBefore(logger, " device/fireRegList 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageindex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pagesize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;
            int type = jsonRequest.containsKey("type") ? jsonRequest.getInt("type") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            List<RegFireCheck> list = regFireCheckService.getRegList(user,pageindex,pagesize,type);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     * 动火申请操作
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/regFireCheck",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject regFireCheck(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/regFireCheck 接收的参数： " + requestParam);
            logBefore(logger, "device/regFireCheck 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int check_id = jsonRequest.containsKey("check_id") ? jsonRequest.getInt("check_id") : 0;
            Integer check_state = jsonRequest.containsKey("check_state") ? jsonRequest.getInt("check_state") : null;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            RegFireCheck regFireCheck = regFireCheckService.findById(check_id);
            if(regFireCheck==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该申请不存在"),true,true);
            }

            if(check_state == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }

            regFireCheck.setCheckState(check_state);
            if(check_state == 1){
                regFireCheck.setCheckResult("审核未通过");
            }else if(check_state == 2){

                regFireCheck.setCheckResult("批准使用");
            }
            regFireCheck.setCheckTime(new Date());
            boolean bl = regFireCheckService.updateById(regFireCheck);
            if(bl){
                sendHttpRequestFire(regFireCheck.getDeviceNum(),regFireCheck.getDeviceId(),check_state);
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),false,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),false,false);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/list",e);
        }
        return result;
    }

    /**
     *  设置动火设备的开关开启
     * @param sn
     * @param device_id
     * @param check_state
     */
    private void sendHttpRequestFire(String sn,Integer device_id,Integer check_state){
        String state = "0";
        if(check_state == 1){
            state = "0";
        }else{
            state = "1";
        }
        String url = "https://chargesocket.tlrobo.cn/ajax/showhow/openorclose.ashx?sn="+  sn +"&open=" + state;
        System.out.println("url:" + url);
        String result = WXPayCommonUtil.httpsRequest(url, "GET","");
        System.out.println("请求电焊机的操作返回结果：" + result);
        //{"code":1,"res":true,"msg":"已发送"}
        if(StrUtil.isNotEmpty(result)){
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if(jsonObject!=null){
                boolean bl = jsonObject.getBool("res");
                if(bl){
                    Device device = deviceService.findById(device_id);
                    if(device!=null){
                        if(check_state == 1){//不同意
                            device.setOnlineState(0);
                        }else if(check_state == 2){
                            device.setOnlineState(1);
                        }
                        deviceService.updateById(device);
                    }
                }
            }
        }
    }

    /**
     * 终端设备信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/detail",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/detail 接收的参数： " + requestParam);
            logBefore(logger, "device/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String terminal_num = jsonRequest.containsKey("terminal_num") ? jsonRequest.getStr("terminal_num") : "";
            int fitting_id = jsonRequest.containsKey("fitting_id") ? jsonRequest.getInt("fitting_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 1;
            if(shop_id == 0){
                shop_id = 1;
            }

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            QueryWrapper<CkTerminal> qw1 = new QueryWrapper<>();
            qw1.eq("shop_id",shop_id);
            qw1.eq("terminal_num",terminal_num);
            CkTerminal terminal = ckTerminalService.getOne(qw1);
            if(terminal==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您终端不存在"),true,true);
            }

//            Shop shop = shopService.findById(terminal.getShopId());
            if(shop != null){
                terminal.setShopName(shop.getShopName());
            }

            if(sysUser.getUserType() >= 4){
                if(sysUser.getShopId() != terminal.getShopId()){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端不属于您的企业"),true,true);
                }
            }else if(sysUser.getUserType() == 2 || sysUser.getUserType() == 3){
                UserShopRelation relation = userShopRelationService.getRelation(terminal.getShopId(),sysUser.getUserId());
                if(relation == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端不属于您的企业"),true,true);
                }
            }
            List<SysDict> dictDOS = sysDictService.selectListByColumn("type","check-state");
            terminal.setDicts(dictDOS);
            map.put("terminal",terminal);
            List<String> fittingNames = new ArrayList<>();
            List<TerminalFitting> fittings = new ArrayList<>();
            if(fitting_id > 0){
                fittings = terminalFittingService.selectListByColumn("id",fitting_id);
            }else{
                fittings = terminalFittingService.selectListByColumn("terminal_id",terminal.getId());
            }
            if(fittings != null){
                for (TerminalFitting fitting : fittings){
                    fittingNames.add(fitting.getDeviceFittingName());
                }
            }
            map.put("fittings",fittings);
            map.put("fittings_name",fittingNames);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/detail",e);
        }
        return result;
    }

    /**
     * 筒仓的二维码信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/qrCode/detail",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject rangeQrCodeDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/qrCode/detail 接收的参数： " + requestParam);
            logBefore(logger, "device/range/qrCode/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int qr_code_id = jsonRequest.containsKey("qr_code_id") ? jsonRequest.getInt("qr_code_id") : 0;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }


            DeviceRangeQrCode rangeQrCode = deviceRangeQrCodeService.findById(qr_code_id);
            if(rangeQrCode == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该二维码不存在"),true,true);
            }

            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            rangeQrCode.setShopName(shop.getShopName());

            map.put("qrCode",rangeQrCode);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/detail",e);
        }
        return result;
    }

    /**
     * 上报筒仓的进出料的记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/add/feed/record",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject addFeedRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/add/feed/record 接收的参数： " + requestParam);
            logBefore(logger, "device/range/add/feed/record 接收的参数： "+requestParam);

            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int qr_code_id = jsonRequest.containsKey("qr_code_id") ? jsonRequest.getInt("qr_code_id") : 0;
            double weight = jsonRequest.containsKey("weight") ? jsonRequest.getDouble("weight") : 0d;
            String feedType = jsonRequest.containsKey("feed_type") ? jsonRequest.getStr("feed_type") : "";


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            if(StrUtil.isEmpty(feedType)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"物料类型不能为空"),true,true);
            }


            DeviceRangeQrCode rangeQrCode = deviceRangeQrCodeService.findById(qr_code_id);
            if(rangeQrCode == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该二维码不存在"),true,true);
            }

            rangeQrCode.setFeedType(feedType);
            boolean bl = deviceRangeQrCodeService.updateById(rangeQrCode);
            if(!bl){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"物料类型修改失败"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            DeviceRangeFeedRecord feedRecord = new DeviceRangeFeedRecord();
            feedRecord.setQrCodeId(qr_code_id);
            feedRecord.setQrCodeName(rangeQrCode.getQrName());
            feedRecord.setWxUserId(user_id);
            feedRecord.setCreateTime(new Date());
            feedRecord.setWeight(weight);
            feedRecord.setShopId(rangeQrCode.getShopId());
            feedRecord.setShopName(shop.getShopName());
            feedRecord.setSysUserId(sysUser.getUserId());
            feedRecord.setSysUserName(sysUser.getName());
            feedRecord.setInOrOut(rangeQrCode.getCodeType());
            feedRecord.setFeedType(feedType);

            int ret = deviceRangeFeedRecordService.addFeedRecord(feedRecord);
            if(ret > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功"),true,true);
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败，请重试"),true,true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/detail",e);
        }
        return result;
    }

    /**
     * 筒仓的进出料的记录列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/feed/record/list",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject feedRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/feed/record/list 接收的参数： " + requestParam);
            logBefore(logger, "device/range/feed/record/list 接收的参数： "+requestParam);

            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int qr_code_id = jsonRequest.containsKey("qr_code_id") ? jsonRequest.getInt("qr_code_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 0;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            QueryWrapper<DeviceRangeFeedRecord> qw = new QueryWrapper<>();
            qw.eq("qr_code_id",qr_code_id);
            qw.orderByDesc("create_time");
            List<DeviceRangeFeedRecord> records = deviceRangeFeedRecordService.getPageEntityList(qw,pageIndex,pageSize);
            map.put("records",records);
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",records.size(),map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/detail",e);
        }
        return result;
    }

    /** 终端设备信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/detail",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject rangeDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/detail 接收的参数： " + requestParam);
            logBefore(logger, "device/range/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;

            User user = userService.findById(user_id);

            DeviceRange range = deviceRangeService.findById(device_id);
            if(range==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您终端不存在"),true,true);
            }

            Shop shop = shopService.findById(user.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }


            QueryWrapper<DeviceRangeResult> qwResult = new QueryWrapper<>();
            qwResult.eq("device_id",range.getId());
            if(user.getIsTest() == 0){
                qwResult.eq("is_test", user.getIsTest()!= null ? user.getIsTest() : 0);
            }
            if(range.getLastVolumeNew() < 0){
                range.setLastVolumeNew(0d);
            }
            qwResult.orderByDesc("create_time");
            qwResult.last("limit 1");
            DeviceRangeResult lastResult = deviceRangeResultService.getOne(qwResult);
            if(lastResult != null){
                range.setLastResult(lastResult);
                range.setLastComputeTime(lastResult.getCreateTime());

                if(lastResult.getTemperature()!= null && lastResult.getHumidity()!= null){
                    if(Double.parseDouble(lastResult.getTemperature()) > 0 && Double.parseDouble(lastResult.getHumidity()) == 0){
                        range.setTemperature(MathUtil.getDoubleUp(Double.parseDouble(lastResult.getTemperature()) * 0.1)+"");
                    }
                }

                if(lastResult.getWeight() != null){
                    range.setTotalWeightDun(MathUtil.getDoubleUp(lastResult.getWeight() / 1000));
                    range.setTotalWeight(MathUtil.getDoubleUp(lastResult.getWeight() / 1000));

                    if(range.getNewMethodWeight()!= null && range.getNewMethodWeight()> 0){
                        range.setTotalWeightDunNew(MathUtil.getDoubleUp((lastResult.getWeight() + range.getNewMethodWeight()) / 1000));
                    }
                }
                if(range.getDeviceType() == 1){
                    range.setMeasureSeconds(5 * 1000);
                }
            }

//            Shop shop = shopService.selectById(range.getShopId());
            if(shop!=null){
                range.setShopName(shop.getShopName());
            }

            map.put("deviceRange",range);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/detail",e);
        }
        return result;
    }

    /**
     * 修改 体积数和吨数
     * @param
     * @throws Exception
     */
    @PostMapping(value="/range/changeData")
    @ResponseBody
    public JSONObject rangeChangeData(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "device/active接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? Integer.parseInt(jsonRequest.getStr("user_id")) : 0;
            int device_id = jsonRequest.containsKey("device_id") ? Integer.parseInt(jsonRequest.getStr("device_id")) : 0;
            double total_volume = jsonRequest.containsKey("total_volume") ? jsonRequest.getDouble("total_volume") : 0d;
            double total_weight = jsonRequest.containsKey("total_weight") ? jsonRequest.getDouble("total_weight") : 0d;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            DeviceRange device = deviceRangeService.findById(device_id);
            if(device == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }


            Shop shop = shopService.findById(device.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            QueryWrapper<DeviceRangeResult> qwResult = new QueryWrapper<>();
            qwResult.eq("device_id", device_id);
            qwResult.orderByDesc("create_time");
            qwResult.last("limit 1");
            DeviceRangeResult lastResult = deviceRangeResultService.getOne(qwResult);
            if(lastResult != null) {
                double weight = lastResult.getWeight();
                weight += total_weight * 1000;
                lastResult.setWeight(weight);
            }
            boolean bl = deviceRangeResultService.updateById(lastResult);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"修改成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"更新失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/detail",e);
        }
        return result;
    }

    /**
     * 终端设备信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/range/lastData",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject rangeDataDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/range/lastData 接收的参数： " + requestParam);
            logBefore(logger, "device/range/lastData 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String device_num = jsonRequest.containsKey("device_num") ? jsonRequest.getStr("device_num") : null;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 20;

            DeviceRange range = deviceRangeService.getDeviceInfoByNum(device_num);
            if(range == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您终端不存在"),true,true);
            }


            Shop shop = shopService.findById(range.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
            }
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            QueryWrapper<DeviceRangeResult> qwResult = new QueryWrapper<>();
            qwResult.eq("device_num", device_num);
            qwResult.orderByDesc("create_time");
            qwResult.last("limit 1");
            DeviceRangeResult lastResult = deviceRangeResultService.getOne(qwResult);
            if(lastResult!= null){

                //判断当前是否需要重置 记录表
                String tableName = lastResult.getRecordTableName();
                // 配置表名
                Map<String,Object> mapTable = new HashMap<>();
                mapTable.put("ck_device_range_record", tableName);
                RequestDataHelper.setRequestData(mapTable);

            }

            QueryWrapper<DeviceRangeRecord> qw = new QueryWrapper<>();
            qw.eq("device_num",device_num);
            qw.eq("order_num", "06");
            qw.last("limit 1");
            qw.orderByDesc("create_time");
            DeviceRangeRecord record = deviceRangeRecordService.getOne(qw);

            map.put("record",record);
            map.put("temperature",range.getTemperature());
            map.put("humidity",range.getHumidity());
            map.put("onlineState", range.getOnlineState());
            map.put("lastOnlineTime", range.getLastOnlineTime());
            map.put("lastOfflineTime", range.getLastOfflineTime());
            map.put("lastComputeTime", range.getLastComputeTime());
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("terminal/detail",e);
        }
        return result;
    }

    /**
     *  重置redis 数据
     * @param
     * @throws Exception
     */
    @GetMapping(value="/reset/range/redis/{id}")
    public JSONObject resetRedis(@PathVariable("id") Integer charger_id){
        JSONObject result = null;
        try{
            DeviceRange range = deviceRangeService.findById(charger_id);
            if(range == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }

            //激活后清除设备缓存
            String key = "device_range_" + range.getDeviceNum();
            redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(range));

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    @PostMapping(value = "/yangan/warning")
    @ResponseBody
    public JSONObject yanganWarning(@RequestBody String requestParam) {
        JSONObject result = null;
        try {
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            System.out.println("烟感报警请求：" + jsonRequest);
            logger.info("烟感报警请求：" + jsonRequest);
            JSONObject dataJson = jsonRequest.getJSONObject("data");
            if(dataJson!=null){
                String serialNumber = dataJson.getStr("serialNumber");

                Device ipVoiceDevice = null;
                SmokeAlarmInfo alarmInfo = new SmokeAlarmInfo();
                QueryWrapper<Device> qw = new QueryWrapper<>();
                qw.eq("device_num", serialNumber);
                qw.eq("device_type", 6);
                qw.last("limit 1");
                Device device = deviceService.getOne(qw);
                if(device != null){
                    alarmInfo.setCompanyId(device.getShopId());
                    alarmInfo.setDeviceNum(device.getDeviceNum());
                    alarmInfo.setDeviceName(device.getDeviceName());
                    Shop shop = shopService.findById(device.getShopId());
                    if(shop!= null){
                        alarmInfo.setCompanyName(shop.getShopName());
                    }
                    ipVoiceDevice = deviceService.findById(device.getIpVoiceId());
                }
                System.out.println("SN编号：" + serialNumber);
                alarmInfo.setSerialNumber(serialNumber);
                alarmInfo.setEventType(jsonRequest.getStr("event"));
                alarmInfo.setTimeStamp(jsonRequest.getStr("timeStamp"));
                alarmInfo.setDeviceId(dataJson.getStr("deviceId"));
                alarmInfo.setContent(dataJson.getStr("content"));
//                if(alarmInfo.getTimeStamp()!=null){
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                }
                alarmInfo.setAlarmTime(new Date());
                alarmInfo.setCreateTime(new Date());

                boolean bl = smokeAlarmInfoService.save(alarmInfo);
                if(bl){
                    //音柱报警线程
                    if(ipVoiceDevice != null){
                        deviceService.syncDataToIpVoice(ipVoiceDevice, device.getIpVoiceUrl());
                    }
                    // 发送推送消息
                    wxTemplateService.sendWxMsgSmokeWarning(alarmInfo);
                }
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    @PostMapping(value = "/yangan/test")
    @ResponseBody
    public JSONObject yanganTest(@RequestBody String requestParam) {
        JSONObject result = null;
        try {
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            System.out.println("烟感报警请求：" + jsonRequest);
            logger.info("烟感报警请求：" + jsonRequest);
//            JSONObject dataJson = jsonRequest.getJSONObject("data");
//            if(dataJson!=null){
                String serialNumber = jsonRequest.getStr("serialNumber");

                Device ipVoiceDevice = null;
                SmokeAlarmInfo alarmInfo = new SmokeAlarmInfo();
                QueryWrapper<Device> qw = new QueryWrapper<>();
                qw.eq("device_num", serialNumber);
                qw.eq("device_type", 6);
                qw.last("limit 1");
                Device device = deviceService.getOne(qw);
                if(device != null){
                    ipVoiceDevice = deviceService.findById(device.getIpVoiceId());
                    //音柱报警线程
                    if(ipVoiceDevice != null){
                        deviceService.syncDataToIpVoice(ipVoiceDevice, device.getIpVoiceUrl());
                    }
                }

                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
//            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }




    /**
     *  烟雾报警记录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/smoke/record/list",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject smokeRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/smoke/record/list 接收的参数： " + requestParam);
            logBefore(logger, " device/smoke/record/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            QueryWrapper<SmokeAlarmInfo> qw = new QueryWrapper<>();
            if(user.getIsTest() == 0){
                qw.eq("company_id", user.getShopId());
            }
            qw.orderByDesc("create_time");
            List<SmokeAlarmInfo> list = smokeAlarmInfoService.getPageEntityList(qw,pageIndex,pageSize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            sysErrorService.insertSelective("smoke/record/list",e);
        }
        return result;
    }

    /** 巡检记录的图片上传
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/uploadImg",method = {RequestMethod.POST, RequestMethod.GET},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject uploadImg(@RequestParam("record_id") int record_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            TerminalCheckRecord record = terminalCheckRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("record_id==" + record_id);

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix) || "mp4".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_TERMINAL_RECORD_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        TerminalCheckRecordImg img = new TerminalCheckRecordImg();
                                        img.setRecordId(record_id);
                                        img.setImgUrl(img_key);
                                        terminalCheckRecordImgService.save(img);
                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            sysErrorService.insertSelective("device/uploadImg",e);
        }
        return result;
    }

    /** 巡检记录的图片上传
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/welding/uploadImg",method = {RequestMethod.POST, RequestMethod.GET},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject weldingUploadImg(@RequestParam("record_id") int record_id,@RequestParam("img_type") int img_type, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            DeviceWeldingRecord record = deviceWeldingRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("record_id==" + record_id);
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix) || "mp4".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_WELDING_RECORD_PHOTOS;
                                        String filePath1 = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date());
                                        String img_key = filePath1 + "/" + fileName;
                                        File file = new File(uploadPath + filePath1);
                                        if(!file.exists()){
                                            file.mkdirs();
                                        }

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        System.out.println("上传图片：" + img_key);

                                        DeviceWeldingRecordImg img = new DeviceWeldingRecordImg();
                                        img.setRecordId(record_id);
                                        img.setImgUrl(img_key);
                                        img.setImgType(img_type);
                                        deviceWeldingRecordImgService.save(img);

                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            sysErrorService.insertSelective("device/uploadImg",e);
        }
        return result;
    }

    /**
     *  修改节点饲料
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/editNodeFeed",method = {RequestMethod.POST}, produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject editNodeFeed(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            System.out.println("device/editNodeFeed 接收的参数： " + requestParam);
            logBefore(logger, " device/editNodeFeed 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int node_id = jsonRequest.containsKey("node_id") ? jsonRequest.getInt("node_id") : 0;
            int feed_id = jsonRequest.containsKey("feed_id") ? jsonRequest.getInt("feed_id") : 0;
            String feed_name = jsonRequest.containsKey("feed_name") ? jsonRequest.getStr("feed_name") : "";
            if(feed_id == -1){ //清空
                UpdateWrapper<DeviceNode> nodeUpdateWrapper = new UpdateWrapper<>();
                nodeUpdateWrapper.eq("id", node_id);
                nodeUpdateWrapper.set("feed_id", null);
                nodeUpdateWrapper.set("feed_name", null);
                deviceNodeService.update(nodeUpdateWrapper);
            }else {
                UpdateWrapper<DeviceNode> nodeUpdateWrapper = new UpdateWrapper<>();
                nodeUpdateWrapper.eq("id", node_id);
                nodeUpdateWrapper.set("feed_id", feed_id);
                nodeUpdateWrapper.set("feed_name", feed_name);
                nodeUpdateWrapper.set("ignor_time",  DateUtil.getAfterDateMinute(5));
                deviceNodeService.update(nodeUpdateWrapper);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            sysErrorService.insertSelective("device/editNodeFeed",e);
        }
        return result;
    }
}
